#include <jni.h>
#include "utils.h"

JNIEXPORT jobject JNICALL
Java_com_yochi_pictureseditor_effects_effectsimpl_EffectAddNoize_process(JNIEnv* env, jobject this, jobject imageObject, jint parameter) {


	/* ------ Parse entries ------ */

	// get entry image
	jclass imageimplClass = 		(*env)->GetObjectClass(env, imageObject);


	/* ------ Parse entries ------ */

	// image constructor methods
	jmethodID midConstructor = 		(*env)->GetMethodID(env, imageimplClass, "<init>", 			"(III)V");

	// image getter methods
	jmethodID midGetHauteur = 		(*env)->GetMethodID(env, imageimplClass, "getHauteur", 		"()I");
	jmethodID midGetLargeur = 		(*env)->GetMethodID(env, imageimplClass, "getLargeur", 		"()I");
    jmethodID midGetProfondeur = 	(*env)->GetMethodID(env, imageimplClass, "getProfondeur", 	"()I");
    jmethodID midGetPixel = 		(*env)->GetMethodID(env, imageimplClass, "getPixel", 		"(III)C");
    jmethodID midGetAveragePixel = 	(*env)->GetMethodID(env, imageimplClass, "getAveragePixel", "(II)C");

    // image setter methods
    jmethodID midSetPixel = 		(*env)->GetMethodID(env, imageimplClass, "setPixel", 		"(IIIC)V");


    /* ------ Recover attributes ------ */

    // get image parameters
    int hauteur = 					(*env)->CallIntMethod(env, imageObject, midGetHauteur);
    int largeur = 					(*env)->CallIntMethod(env, imageObject, midGetLargeur);
    int profondeur = 				(*env)->CallIntMethod(env, imageObject, midGetProfondeur);


    /* ------ Instantiate result image ------ */

    jobject imageResult = 			imageObject;

    /* ------ Process effect ------ */

    int p, l, h;
    int luck;
    char noize;

    for(p=0; p<profondeur; p++) {
    	for(l=0; l<largeur; l++) {
    		for(h=0; h<hauteur; h++) {

    			if( (profondeur == 4 && p < 3)  ||  (profondeur == 2 && p < 1) ) {

    				// compute luck to compare with parameter
    				luck = randomValue(0, 101);

    				if(luck < parameter)  {
    					// compute random new pixel value
    					noize = randomValue(0, 256);
    					(*env)->CallVoidMethod(env, imageResult, midSetPixel, p, l, h, noize);

    				} /* else {
    					// re-use previous pixel value
    				} */
    			}

    		}
    	}
    }

    return imageResult;
}
